package cn.com.dashihui.api.ITask.kit;


import cn.com.dashihui.api.common.SysPara;
import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.pay.SQ.Kit.ParamUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class PingAnUtils
{
  public static String getHead(String hLength, TreeMap<String, String> headMap)
    throws Exception
  {
    StringBuffer buffer = new StringBuffer();
    buffer.append("A001");
    buffer.append("26");
    buffer.append("01");
    buffer.append("01");
    String qydm = ParamUtils.toString(headMap.get("Qydm"));
    buffer.append(qydm).append(getSpaceStr(20 - qydm.length()));
    buffer.append(hLength);
    buffer.append("000000");
    buffer.append(getSpaceStr(5));
    buffer.append("01");
    buffer.append(DatetimeKit.getFormatDate(new Date(), "yyyyMMddHHmmss"));
    buffer.append(ParamUtils.toString(headMap.get("ThirdLogNo")));
    buffer.append("999999");
    buffer.append(getSpaceStr(100));
    buffer.append("0");
    buffer.append("000");
    buffer.append("0");
    buffer.append("0");
    buffer.append(getSpaceStr(12));
    buffer.append("0000000000");
    buffer.append("0");

    return buffer.toString();
  }

  public static String getBusinessHead(String hLength, TreeMap<String, String> headMap) throws Exception {
    StringBuffer buffer = new StringBuffer();
    buffer.append(ParamUtils.toString(headMap.get("TranFunc")));
    buffer.append("01");
    buffer.append(getSpaceStr(16));
    buffer.append(DatetimeKit.getFormatDate(new Date(), "yyyyMMddHHmmss"));
    buffer.append("999999");
    buffer.append(getSpaceStr(42));
    buffer.append("0");
    buffer.append(hLength);
    buffer.append("C" + CommonKit.randomNum(4));
    buffer.append(ParamUtils.toString(headMap.get("ThirdLogNo")));
    buffer.append(ParamUtils.toString(headMap.get("Qydm")));

    return buffer.toString();
  }

  public static String getBody(TreeMap<String, String> bodyMap) throws Exception {
    StringBuffer buffer = new StringBuffer();

    for (String key : bodyMap.keySet()) {
      if (bodyMap.containsKey(key)) {
        buffer.append(ParamUtils.toString(bodyMap.get(key))).append("&");
      }
    }

    return buffer.toString();
  }

  


  public static String getZero(int length) {
    String[] spStr = new String[length];
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < spStr.length; i++) {
      buffer.append("0");
    }
    return buffer.toString();
  }
  
  public static HashMap<String, String> send(Map<String, Object> paraMap, String service, String seq)
    throws Exception
  {
    Socket socket = null;
    OutputStream outputStream = null;
    InputStream inputStream = null;
    try {
      String address = ParamUtils.toString(paraMap.get("REQUEST_URL")).split(":")[0];
      int port = Integer.parseInt(ParamUtils.toString(paraMap.get("REQUEST_URL")).split(":")[1]);

      socket = new Socket(address, port);
      socket.setSendBufferSize(4096);
      socket.setTcpNoDelay(true);
      socket.setSoTimeout(60000);
      socket.setKeepAlive(true);

      outputStream = socket.getOutputStream();
      inputStream = socket.getInputStream();

      String requestStr = ParamUtils.toString(paraMap.get("REQUEST_STR"));

      outputStream.write(requestStr.getBytes(SysPara.GBK));
      outputStream.flush();

      int headLength = 222;

      byte[] headByte = new byte[headLength];
      int readHeadCount = 0;
      while (readHeadCount < headLength) {
        readHeadCount += inputStream.read(headByte, readHeadCount, headLength - readHeadCount);
      }

      byte[] busByte = Arrays.copyOfRange(headByte, 30, 40);
      int busLength = Integer.parseInt(new String(busByte, SysPara.GBK));

//      LoggerUtils.info(service, seq, "长度", busLength);

      byte[] bodyByte = new byte[busLength];
      int readBodyCount = 0;
      while (readBodyCount < busLength) {
        readBodyCount += inputStream.read(bodyByte, readBodyCount, busLength - readBodyCount);
      }

      String respStr = new String(headByte, SysPara.GBK) + new String(bodyByte, SysPara.GBK) + '\000';
//      LoggerUtils.info(service, seq, "响应", respStr);

      outputStream.close();
      inputStream.close();
      socket.close();

      return getRespMap(respStr); 
      } catch (Exception e) {
    	  throw new RuntimeException(e);
      }
  
  }

  public static HashMap<String, String> getRespMap(String respStr) throws Exception
  {
    HashMap retKeyDict = new HashMap();
    int i = 0;
    byte[] bNetHead = new byte['Þ'];
    byte[] bTranFunc = new byte['â'];
    byte[] bRspCode = new byte[93];
    byte[] bRspMsg = new byte['Á'];
    byte[] bHeadMsg = new byte[344];
    try {
      byte[] byteRetMessage = respStr.getBytes(SysPara.GBK);
      for (i = 0; i < 93; i++) {
        bRspCode[i] = byteRetMessage[i];
      }
      String sRspCode = new String(bRspCode, SysPara.GBK);
      sRspCode = sRspCode.substring(87);

      retKeyDict.put("RspCode", sRspCode);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
    try
    {
      byte[] byteRetMessage = respStr.getBytes(SysPara.GBK);
      for (i = 0; i < 193; i++) {
        bRspMsg[i] = byteRetMessage[i];
      }
      String sRspMsg = new String(bRspMsg, SysPara.GBK);
      sRspMsg = sRspMsg.substring(93);
      retKeyDict.put("RspMsgBak", sRspMsg);
      sRspMsg = sRspMsg.trim();

      retKeyDict.put("RspMsg", sRspMsg);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }

    String strCode = ParamUtils.toString(retKeyDict.get("RspCode"));

    if ("000000".equals(strCode)) {
      try {
        byte[] byteRetMessage = respStr.getBytes(SysPara.GBK);
        for (i = 0; i < 226; i++) {
          bTranFunc[i] = byteRetMessage[i];
        }
        String sTranFunc = new String(bTranFunc, SysPara.GBK);
        for (i = 0; i < 222; i++) {
          bNetHead[i] = byteRetMessage[i];
        }
        String sNetHead = new String(bNetHead, SysPara.GBK);
        int iTranLength = sNetHead.length();
        sTranFunc = sTranFunc.substring(iTranLength);
        retKeyDict.put("TranFunc", sTranFunc);
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
      try
      {
        byte[] byteRetMessage = respStr.getBytes(SysPara.GBK);
        String sBodyMsg = new String(byteRetMessage, SysPara.GBK);
        for (i = 0; i < 344; i++) {
          bHeadMsg[i] = byteRetMessage[i];
        }
        String sHeadMsg = new String(bHeadMsg, SysPara.GBK);
        int iLength = sHeadMsg.length();
        sBodyMsg = sBodyMsg.substring(iLength);

        retKeyDict.put("BodyMsg", sBodyMsg);
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }

      spiltBodyMap(retKeyDict, ParamUtils.toString(retKeyDict.get("TranFunc")));
    }

    return retKeyDict;
  }

  public static void spiltBodyMap(HashMap<String, String> respMap, String tranFunc) throws Exception {
    if (respMap.containsKey("BodyMsg")) {
      String bodyMessage = ParamUtils.toString(respMap.get("BodyMsg"));
      String[] arry = bodyMessage.split("&");
      if (("6000".equals(tranFunc)) || ("6092".equals(tranFunc))) {
        respMap.put("CustAcctId", ParamUtils.toString(arry[0]));
        respMap.put("Reserve", ParamUtils.toString(arry[1]));
      } else if ("6066".equals(tranFunc)) {
        respMap.put("Reserve", ParamUtils.toString(arry[0]));
      } else if (("6056".equals(tranFunc)) || ("6101".equals(tranFunc)) || ("6085".equals(tranFunc))) {
        respMap.put("FrontLogNo", ParamUtils.toString(arry[0]));
        respMap.put("Reserve", ParamUtils.toString(arry[1]));
      } else if ("6082".equals(tranFunc)) {
        respMap.put("RevMobilePhone", ParamUtils.toString(arry[0]));
        respMap.put("SerialNo", ParamUtils.toString(arry[1]));
        respMap.put("Reserve", ParamUtils.toString(arry[2]));
      } else if ("6110".equals(tranFunc)) {
        respMap.put("TranFlag", ParamUtils.toString(arry[0]));
        respMap.put("TranStatus", ParamUtils.toString(arry[1]));
        respMap.put("TranAmount", ParamUtils.toString(arry[2]));
        respMap.put("TranDate", ParamUtils.toString(arry[3]));
        respMap.put("TranTime", ParamUtils.toString(arry[4]));
        respMap.put("InCustAcctId", ParamUtils.toString(arry[5]));
        respMap.put("OutCustAcctId", ParamUtils.toString(arry[6]));
        respMap.put("Reserve", ParamUtils.toString(arry[7]));
      } else if ("6093".equals(tranFunc)) {
        respMap.put("ThirdCustId", ParamUtils.toString(arry[0]));
        respMap.put("TotalBalance", ParamUtils.toString(arry[1]));
        respMap.put("TotalFreezeAmount", ParamUtils.toString(arry[2]));
        respMap.put("Reserve", ParamUtils.toString(arry[3]));
      }
    }
  }

  

  public static Map<String, Object> send(Map<String, Object> paraMap, String requestStr) throws Exception
  {
	  
    Socket socket = null;
    OutputStream outputStream = null;
    InputStream inputStream = null;
    try {
      String address = ParamUtils.toString(paraMap.get("REQUEST_URL")).split(":")[0];
      int port = Integer.parseInt(ParamUtils.toString(paraMap.get("REQUEST_URL")).split(":")[1]);
      socket = new Socket(address, port);
      socket.setSendBufferSize(4096);
      socket.setTcpNoDelay(true);
      socket.setSoTimeout(60000);
      socket.setKeepAlive(true);
      System.out.println(  "  send： send： send： send： send： send： send：1");
      outputStream = socket.getOutputStream();
      inputStream = socket.getInputStream();
      System.out.println(  "  send： send： send： send： send： send： send：2");
      outputStream.write(requestStr.getBytes(SysPara.GBK));
      outputStream.flush();

      int headLength = 222;
      byte[] headByte = new byte[headLength];
      int readHeadCount = 0;
      while (readHeadCount < headLength) {
        readHeadCount += inputStream.read(headByte, readHeadCount, headLength - readHeadCount);
      }

      byte[] busByte = Arrays.copyOfRange(headByte, 30, 40);
      int busLength = Integer.parseInt(new String(busByte, SysPara.GBK));
//      LoggerUtils.info(service, seq, "长度", busLength);

      byte[] bodyByte = new byte[busLength];
      int readBodyCount = 0;
      while (readBodyCount < busLength) {
        readBodyCount += inputStream.read(bodyByte, readBodyCount, busLength - readBodyCount);
      }

      String respStr = new String(headByte, SysPara.GBK) + new String(bodyByte, SysPara.GBK) + '\000';
//      LoggerUtils.info(service, seq, "响应", respStr);

      outputStream.close();
      inputStream.close();
      socket.close();

      return getRespYqMap(new String(headByte, SysPara.GBK), new String(bodyByte, SysPara.GBK)); 
      } catch (Exception e) {
    	  throw e;
      }
    
  }

  private static Map<String, Object> getRespYqMap(String headStr, String bodyStr)
  {
    Map respMap = new HashMap();

    String resCode = headStr.substring(87, 93).trim();
    if ("000000".equals(resCode)) {
      respMap.put("RESP_CODE", resCode);
      respMap.put("RESP_MSG", headStr.substring(93, 193).trim());
      respMap.put("BUS_BODY", bodyStr);
    } else {
      respMap.put("RESP_CODE", resCode);
      respMap.put("RESP_MSG", "转账失败，具体原因请联系银行");
    }

    return respMap;
  }
  

  public static String getYQHead(String bLength, Map<String, Object> headMap) throws Exception {
    StringBuffer buffer = new StringBuffer();
    buffer.append("A00101");
    buffer.append("01");
    buffer.append("01");
    buffer.append(ParamUtils.toString(headMap.get("MERCHANTS_ID")));
    buffer.append(getZero(10 - bLength.length()) + bLength);
    String tradeCode = ParamUtils.toString(headMap.get("交易码"));
    buffer.append(tradeCode + getSpaceStr(6 - tradeCode.length()));
    buffer.append("PA001");
    buffer.append("01");
    buffer.append(DatetimeKit.getFormatDate(new Date(), "yyyyMMdd"));
    buffer.append(DatetimeKit.getFormatDate(new Date(), "HHmmss"));
    buffer.append(ParamUtils.toString(headMap.get("REQUEST_ID")));
    buffer.append("000000");
    buffer.append(getZero(100));
    buffer.append("0");
    buffer.append("000");
    buffer.append("0");
    buffer.append("0");
    buffer.append(getZero(12));
    buffer.append(getZero(10));
    buffer.append("0");
    return buffer.toString();
  }

  
  public static String getSpaceStr(int spLength) {
    String[] spStr = new String[spLength];
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < spStr.length; i++) {
      buffer.append(" ");
    }

    return buffer.toString();
  }
}